package com.baibei.ebec.home.newIndex;

import android.content.Context;
import android.util.Log;
import android.util.SparseArray;

import com.baibei.basic.BasicPresenterImpl;
import com.baibei.basic.module.observer.PageDataObservable;
import com.baibei.basic.module.observer.PageObservable;
import com.baibei.ebec.quotation.AppQuotationFilter;
import com.baibei.ebec.quotation.QuotationManager;
import com.baibei.ebec.quotation.event.IQuotationEvent;
import com.baibei.ebec.sdk.ApiFactory;
import com.baibei.ebec.sdk.IOrderApi;
import com.baibei.ebec.sdk.IProductApi;
import com.baibei.ebec.sdk.IQuotationApi;
import com.baibei.ebec.sdk.ITradeApi;
import com.baibei.ebec.sdk.IUserApi;
import com.baibei.model.Area;
import com.baibei.model.BalanceInfo;
import com.baibei.model.BannerInfo;
import com.baibei.model.CouponInfo;
import com.baibei.model.CouponResponseInfo;
import com.baibei.model.CustomerWxInfo;
import com.baibei.model.HelpContentInfo;
import com.baibei.model.HomeIndexInfo;
import com.baibei.model.HomeIndexProductInfo;
import com.baibei.model.MarqueeInfo;
import com.baibei.model.MsgStatusInfo;
import com.baibei.model.NewCategoryInfo;
import com.baibei.model.NewHomeIndexInfo;
import com.baibei.model.NewMarqueeInfo;
import com.baibei.model.NewProductInfo;
import com.baibei.model.OrderInfo;
import com.baibei.model.ProductInfo;
import com.baibei.model.QuotationInfo;
import com.baibei.model.QuotationProductInfo;
import com.baibei.model.RankingInfo;
import com.baibei.model.ServiceQQInfo;
import com.baibei.model.ShipmentInfo;
import com.baibei.model.SuggestNumbersInfo;
import com.baibei.model.TradeTimeInfo;
import com.baibei.model.UserInfo;
import com.baibei.model.XinStatusInfo;
import com.baibei.model.event.UpdateUserInfoEvent;
import com.baibei.quotation.QuotationFilter;
import com.baibei.sdk.ApiDefaultObserver;
import com.baibei.ui.AppUI;
import com.blankj.utilcode.utils.LogUtils;
import com.blankj.utilcode.utils.ToastUtils;
import com.rae.swift.Rx;
import com.rae.swift.session.SessionManager;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.ObservableSource;
import io.reactivex.functions.Action;
import io.reactivex.functions.Function;

import static android.content.ContentValues.TAG;

/**
 * Created by tang on 2018/6/28.
 */

public class NewHomeIndexPresenterImpl extends BasicPresenterImpl<NewHomeIndexContract.View> implements NewHomeIndexContract.Presenter, IQuotationEvent {
    private IProductApi mProductApi;
    private IUserApi mUserApi;
    //    private PageObservable<ShipmentInfo> mPageObservable;
    private List<ShipmentInfo> mDataList;
    private final IQuotationApi mQuotationApi;
    private final ITradeApi mTradeApi;
    private final ArrayList<Integer> mSuggestNumbers;
    private final IOrderApi mOrderApi;
    private List<OrderInfo> mOrderInfos;
    private List<HomeIndexProductInfo> mChildProducts;
    private List<QuotationProductInfo> mQuotationProductInfos;
    private HomeIndexInfo mHomeIndexInfo;

    public NewHomeIndexPresenterImpl(Context context, NewHomeIndexContract.View view) {
        super(context, view);
        //设置指针地址
        setTag(this.toString());
        mProductApi = ApiFactory.getInstance().getProductApi();
        mQuotationApi = ApiFactory.getInstance().getQuotationApi();
        mTradeApi = ApiFactory.getInstance().getTradeApi();
        mUserApi = ApiFactory.getInstance().getUserApi();
        mOrderApi = ApiFactory.getInstance().getOrderApi();
        mSuggestNumbers = new ArrayList<>();
        setTag(this.toString());

        createObservable(mTradeApi.getRankingList(Area.ALL.name()))
                .subscribe(new ApiDefaultObserver<List<RankingInfo>>() {
                    @Override
                    protected void onError(String s) {

                    }

                    @Override
                    protected void accept(List<RankingInfo> rankingInfos) {
                        if (rankingInfos == null) return;
                        if (mView == null) return;
                        mView.onLoadClosePrice(rankingInfos);
                    }
                });

//        mPageObservable = new PageDataObservable<ShipmentInfo>(view) {
//            @Override
//            protected io.reactivex.Observable onCreateObserver(int page) {
//                return createObservable(mProductApi.queryShipment(mView.getArea().name(), page));
//            }
//
//            @Override
//            protected void onLoadDataComplete(List<ShipmentInfo> dataList) {
//                super.onLoadDataComplete(dataList);
//                mDataList = dataList;
//                if (mView != null) {
//                    mView.onLoadComplete();
//                    mView.refreshCompleted();
//                }
//                // 在从缓存里面读取
//                QuotationManager.getInstance().flushCache();
//            }
//
//            @Override
//            protected void onNoMoreData() {
//                super.onNoMoreData();
//                if (mView != null) {
//                    mView.onLoadComplete();
//                    mView.refreshCompleted();
//                }
//            }
//
//
//            @Override
//            protected void onLoadData(int page) {
//                super.onLoadData(page);
//                if (mView != null) {
//                    mView.refreshCompleted();
//                }
//            }
//        };


        // 注册行情
        QuotationFilter filter = new QuotationFilter(QuotationFilter.ACTION_QUOTATION_PRODUCT);
        filter.addAction(AppQuotationFilter.ACTION_TRADE_CREATED);
        filter.addAction(AppQuotationFilter.ACTION_TRADE_CLOSED);
        filter.addAction(AppQuotationFilter.ACTION_MARKET_STATUS);
        QuotationManager.getInstance().register(this, filter);
    }

    @Override
    public void start() {
        super.start();

        if (mView != null) {
            loadBasicData();
            if (SessionManager.getDefault().isLogin()) {
                loadBalanceAndCoupons();
                loadRepeated();
            }
        }

        if (mView.getArea() == Area.ALL) {
            createObservable(mProductApi.getBannerInfos()).subscribe(new ApiDefaultObserver<List<BannerInfo>>() {
                @Override
                protected void onError(String s) {
                    if (mView != null) {
                        mView.onLoadBannerFailed(s);
                    }
                }

                @Override
                protected void accept(List<BannerInfo> bannerInfos) {
                    if (bannerInfos == null) return;
                    if (mView != null) {
                        mView.onLoadBannerData(bannerInfos);
                    }
                }
            });
        }
    }

    public void loadRepeated() {
        //获取订单列表
        createObservable(mOrderApi.getOrderList()).subscribe(new ApiDefaultObserver<List<OrderInfo>>() {
            @Override
            protected void onError(String s) {
                if (mView != null) {
                    mView.onLoadOrderListFailed(s);
                }
            }

            @Override
            protected void accept(List<OrderInfo> orderInfos) {
                if (orderInfos == null) return;
                mOrderInfos = orderInfos;
                if (mView != null) {
                    mView.updateMyIncome(orderInfos);
                }
            }
        });
    }

    public void loadBalanceAndCoupons() {
        createObservable(mUserApi.queryCouponInfos())
                .flatMap(new Function<CouponResponseInfo, ObservableSource<SuggestNumbersInfo>>() {
                    @Override
                    public ObservableSource<SuggestNumbersInfo> apply(CouponResponseInfo couponResponseInfo) throws Exception {
                        return createObservable(mTradeApi.getSuggestNumbers());
                    }
                })
                .flatMap(new Function<SuggestNumbersInfo, ObservableSource<BalanceInfo>>() {
                    @Override
                    public ObservableSource<BalanceInfo> apply(SuggestNumbersInfo suggestNumbersInfo) throws Exception {
                        mSuggestNumbers.clear();
                        String[] numberArray = suggestNumbersInfo.getNumbers().split(",");
                        for (int i = 0; i < numberArray.length; i++) {
                            mSuggestNumbers.add(i, Rx.parseInt(numberArray[i]));
                        }
                        return createObservable(mUserApi.getBalanceInfo());
                    }
                })
                .subscribe(new ApiDefaultObserver<BalanceInfo>() {
                    @Override
                    protected void onError(String s) {
                        if (mView != null) {
                            mView.onLoadBalanceFailed("--");
                        }
                    }

                    @Override
                    protected void accept(BalanceInfo balanceInfo) {
                        if (balanceInfo == null) return;
                        if (mView == null) return;
                        mView.onLoadBalanceInfo(balanceInfo);
                    }
                });

        // 优惠券数量
        createObservable(mUserApi.queryCouponInfos()).subscribe(new ApiDefaultObserver<CouponResponseInfo>() {
            @Override
            protected void onError(String s) {
                if (mView == null) return;
                mView.onLoadCouponFailed();
            }

            @Override
            protected void accept(CouponResponseInfo couponResponseInfo) {
                if (couponResponseInfo == null) return;
                if (mView == null) return;
                mView.onLoadCouponSuccess(couponResponseInfo.getValid(), couponResponseInfo);
            }
        });
    }

    @Override
    public List<Integer> getSuggestNumbers() {
        return mSuggestNumbers;
    }

    @Override
    public void getHelp() {
        createObservable(mTradeApi.getHelp())
                .subscribe(new ApiDefaultObserver<List<HelpContentInfo>>() {
                    @Override
                    protected void onError(String s) {

                    }

                    @Override
                    protected void accept(List<HelpContentInfo> heloInfo) {
                        if (heloInfo == null) return;
                        if (mView == null) return;
                        mView.onLoadHelpSuccess(heloInfo.get(0).getText());
                    }
                });
    }

    @Override
    public void getProductCoupon(String productId) {
        createObservable(mTradeApi.getValidCouponList(productId))
                .subscribe(new ApiDefaultObserver<List<CouponInfo>>() {
                    @Override
                    protected void onError(String s) {
                        mView.onLoadProductCouponFailed();
                    }

                    @Override
                    protected void accept(List<CouponInfo> couponInfos) {
                        if (couponInfos == null) return;
                        mView.onLoadProductCouponSuccess(couponInfos);
                    }
                });
    }

    @Override
    public void getIfShowXin() {
        createObservable(mUserApi.getIfShowXin()).subscribe(new ApiDefaultObserver<XinStatusInfo>() {
            @Override
            protected void onError(String s) {

            }

            @Override
            protected void accept(XinStatusInfo xinStatusInfo) {
                if (xinStatusInfo == null) return;
                if (mView == null) return;
                mView.onLoadXin(xinStatusInfo);
            }
        });
    }

    @Override
    public void getIfHasNewMsg(String userId, String accessToken) {
        createObservable(mUserApi.getIfHasNewMsg(userId, accessToken)).subscribe(new ApiDefaultObserver<List<MsgStatusInfo>>() {
            @Override
            protected void onError(String s) {

            }

            @Override
            protected void accept(List<MsgStatusInfo> msgStatusInfos) {
                if (msgStatusInfos == null) return;
                if (mView == null) return;
                mView.onLoadMsgStatus(msgStatusInfos);
            }
        });
    }

    @Override
    public void getCustomerWxCode() {
        createObservable(mUserApi.getCustomerWX()).subscribe(new ApiDefaultObserver<CustomerWxInfo>() {
            @Override
            protected void onError(String s) {

            }

            @Override
            protected void accept(CustomerWxInfo customerWxInfo) {
                if (customerWxInfo == null) return;
                mView.onLoadCustomerWXCodeSuccess(customerWxInfo);
            }
        });
    }


    private void loadBasicData() {
//        createObservable(mProductApi.getHomeIndexInfos()).subscribe(new ApiDefaultObserver<HomeIndexInfo>() {
//            @Override
//            protected void onError(String s) {
//
//            }
//
//            @Override
//            protected void accept(HomeIndexInfo homeIndexInfo) {
//                mChildProducts = homeIndexInfo.getIndexDetailDtoList();
//                mQuotationProductInfos = homeIndexInfo.getQuotations();
//                mHomeIndexInfo = homeIndexInfo;
//                if (mView == null) return;
//                mView.onLoadHomeIndexData(homeIndexInfo);
//                mView.refreshCompleted();
//            }
//        });

        createObservable(mProductApi.getHomeIndexInfosNew()).subscribe(new ApiDefaultObserver<NewHomeIndexInfo>() {
            @Override
            protected void onError(String s) {
            }

            @Override
            protected void accept(NewHomeIndexInfo newHomeIndexInfo) {
                if (newHomeIndexInfo == null){
                    return;
                }
                //把新接口数据格式转换成旧接口格式，请原谅我不想动首页的逻辑了。
                HomeIndexInfo homeIndexInfo = format(newHomeIndexInfo);
                mChildProducts = homeIndexInfo.getIndexDetailDtoList();
                mQuotationProductInfos = homeIndexInfo.getQuotations();
                mHomeIndexInfo = homeIndexInfo;
                if (mView == null) return;
                mView.onLoadHomeIndexData(homeIndexInfo);
                mView.refreshCompleted();
            }
        });

        createObservable(mQuotationApi.getTradeTimeInfo()).subscribe(new ApiDefaultObserver<TradeTimeInfo>() {
            @Override
            protected void onError(String s) {

            }

            @Override
            protected void accept(TradeTimeInfo tradeTimeInfo) {
                if (tradeTimeInfo == null){
                    return;
                }
                if (mView != null) {
                    mView.onLoadTradeTimeInfo(tradeTimeInfo);
                }
            }
        });
    }

    private HomeIndexInfo format(NewHomeIndexInfo newHomeIndexInfo) {
        List<NewCategoryInfo> categoryList = newHomeIndexInfo.getCategoryList();
        ArrayList<QuotationProductInfo> quotations = new ArrayList<>();
        ArrayList<HomeIndexProductInfo> indexDetailDtoList = new ArrayList<>();
        for (NewCategoryInfo info : categoryList) {
            QuotationProductInfo quotationProductInfo = new QuotationProductInfo();
            quotationProductInfo.setQuoteName(info.getQuoteName());
            quotationProductInfo.setLastPrice(Rx.parseDouble(info.getLastPrice()));
            quotationProductInfo.setProductId("" + info.getProductId());
            quotationProductInfo.setName(info.getName());
            quotationProductInfo.setClose(Rx.parseDouble(info.getClosePrice()));
            quotationProductInfo.setArea(info.getArea());
            quotations.add(quotationProductInfo);

            ArrayList<ProductInfo> child = new ArrayList<>();

            for (NewProductInfo indexInfo : info.getProductList()) {
                ProductInfo productInfo = new ProductInfo();
                productInfo.setQuoteName(indexInfo.getQuoteName());
                productInfo.setProductPic((String) indexInfo.getProductPic());
                productInfo.setLastPrice(Rx.parseDouble(indexInfo.getLastPrice()));
                productInfo.setProductId("" + indexInfo.getProductId());
                productInfo.setFee(indexInfo.getFee());
                productInfo.setClosePrice(indexInfo.getClosePrice());
                productInfo.setProductDetails((String) indexInfo.getDetailPic());
                productInfo.setTicketId((String) indexInfo.getTicketId());
                productInfo.setPrice(indexInfo.getPrice());
                productInfo.setArea(indexInfo.getArea());
                productInfo.setName(indexInfo.getName());
                productInfo.setRepertoryStatus(indexInfo.getRepertoryStatus());

                child.add(productInfo);
            }

            HomeIndexProductInfo indexProductInfo = new HomeIndexProductInfo();
            indexProductInfo.setArea(info.getArea());
            indexProductInfo.setParent(quotationProductInfo);
            indexProductInfo.setChild(child);
            indexDetailDtoList.add(indexProductInfo);
        }

        HomeIndexInfo homeIndexInfo = new HomeIndexInfo();
        homeIndexInfo.setQuotations(quotations);
        homeIndexInfo.setIndexDetailDtoList(indexDetailDtoList);
        return homeIndexInfo;
    }

    @Override
    public void destroy() {
        QuotationManager.getInstance().unregister(this);
//        mPageObservable.destroy();
        super.destroy();
    }

    @Override
    @Subscribe
    public void onEvent(SparseArray<QuotationInfo> quotations) {
        // 刷新列表
        if (Rx.isEmpty(mQuotationProductInfos) || Rx.isEmpty(mChildProducts) || mView == null) {
            return;
        }
        //更新具体商品
        for (HomeIndexProductInfo childProduct : mChildProducts) {
            List<ProductInfo> products = childProduct.getChild();
            if (Rx.isEmpty(products)) {
                continue;
            }
            //黄金白银行情判断
            //每个子item头部数据处理
            QuotationProductInfo quotationProductInfo = childProduct.getParent();
            if (quotationProductInfo == null) {
                continue;
            }
            QuotationInfo commonQuotationInfo = quotations.get(Rx.parseInt(quotationProductInfo.getProductId()));
            if (commonQuotationInfo != null && commonQuotationInfo.getMarketPrice() != quotationProductInfo.getLastPrice()) {
                quotationProductInfo.setLastPrice(commonQuotationInfo.getMarketPrice());
                mView.onUpdateQuotation(quotationProductInfo);
            }
        }

        if (mOrderInfos == null) {
            return;
        }
        int updateCount = 0;
        for (OrderInfo info : mOrderInfos) {
            //根据现有的订单查找推送行情的改变，如果找到则设置最新价格
            QuotationInfo quotationInfo = quotations.get(Rx.parseInt(info.getProductid()));
            if (quotationInfo == null) continue;
            //如果价格相同，跳过
            if (quotationInfo.getMarketPrice() == info.getLast()) {
                continue;
            }
            LogUtils.e(info.getName() + "----原价格：" + info.getLast() + "  更新价格:" + quotationInfo.getMarketPrice());
            //记录更新数据，如果集合中有需要更新的，刷新界面
            updateCount++;
            info.setLast(quotationInfo.getMarketPrice());
        }
        if (updateCount != 0) {
            mView.updateMyIncome(mOrderInfos);
        }
//        // 刷新列表
//        if (Rx.isEmpty(mDataList) || mView == null) return;
//        int updateCount = 0;
//        for (ShipmentInfo shipmentInfo : mDataList) {
//            List<ProductInfo> products = shipmentInfo.getProducts();
//            if (Rx.isEmpty(products)) {
//                continue;
//            }
//            for (ProductInfo product : products) {
//                QuotationInfo quotationInfo = quotations.get(Rx.parseInt(product.getProductId()));
//                //如果没找到行情，跳过
//                if (quotationInfo == null) {
//                    continue;
//                }
//                //如果价格相同，跳过
//                if (quotationInfo.getMarketPrice() == product.getLastPrice()) {
//                    continue;
//                }
////                LogUtils.e(product.getName() + "----原价格：" + product.getLastPrice() + "  更新价格:" + quotationInfo.getMarketPrice());
//                //记录更新数据，如果集合中有需要更新的，刷新界面
//                updateCount++;
//                product.setLastPrice(quotationInfo.getMarketPrice());
//            }
//        }
//        if (updateCount != 0) {
//            mView.onLoadData(mDataList);
//        }
    }

    @Subscribe
    public void onUpdateUserInfoEvent(UpdateUserInfoEvent event) {
        createObservable(mUserApi.getUserInfo()).subscribe(new ApiDefaultObserver<UserInfo>() {
            @Override
            protected void onError(String s) {

            }

            @Override
            protected void accept(UserInfo userInfo) {
                //保存用户对象
                LogUtils.e("tag--收到指令，并更新用户信息，得到数据:" + userInfo);
                SessionManager.getDefault().setUser(userInfo);
            }
        });
    }

    @Override
    public void getServiceQQ() {
        mView.showLoading();
        createObservable(mUserApi.queryQQUrl()).doFinally(new Action() {
            @Override
            public void run() throws Exception {
                mView.hideLoading();
            }
        }).subscribe(new ApiDefaultObserver<ServiceQQInfo>() {
            @Override
            protected void onError(String s) {
                if (mView == null) return;
                mView.onLoadServiceQQFailed(s);
            }

            @Override
            protected void accept(ServiceQQInfo serviceQQInfo) {
                if (serviceQQInfo == null){
                    return;
                }
                if (mView == null) return;
                mView.onLoadServiceQQSuccess(serviceQQInfo.getQqUrl());
                Log.i("qqur", serviceQQInfo.toString());
            }
        });
    }

    @Override
    public void getMarquee() {
        createObservable(mUserApi.getNewMarquee()).subscribe(new ApiDefaultObserver<List<NewMarqueeInfo>>() {
            @Override
            protected void onError(String s) {
                ToastUtils.showShortToast(s);
            }

            @Override
            protected void accept(List<NewMarqueeInfo> marqueeInfos) {
                if (marqueeInfos == null) return;
                if (mView == null) return;
                mView.onLoadMarquee(marqueeInfos);
            }
        });
    }

//    /**
//     * 多空接口
//     */
//    @Override
//    public void loadUpDownCompare(String area) {
//        try {
//            createObservable(mUserApi.getUpDownCompare(area)).subscribe(new ApiDefaultObserver<UpDwonCompareInfo>() {
//                @Override
//                protected void onError(String s) {
//                    mView.onLoadUpDownCompareFailed();
//                }
//
//                @Override
//                protected void accept(UpDwonCompareInfo info) {
//                    mView.onLoadUpDownCompareSuccess(info);
//                }
//            });
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
}
